package com.boe.rnmf.pkg.configurer;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.boe.rnmf.vo.response.BaseResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 拦截器: 用户-登录-权限校验
 */
public class LoginInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    /**
     * env of dev
     */
    public static final String ENV_DEV = "dev";

    /**
     * 当前激活的配置文件
     */
    @Value("${spring.profiles.active}")
    private String env;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        /**开发环境跳过验证**/
        if (env.equals(ENV_DEV)) {
            return Boolean.TRUE;
        }
        /**如果不是映射到方法直接通过**/
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String authHeader = request.getHeader("token");
        if (StringUtils.isEmpty(authHeader)) {
            logger.info("验证失败");
            print(response, BaseResponse.error(403, "签名验证不存在"));
            return false;
        }

        //TODO 验证TOKEN
        //TODO 验证权限
        return true;
    }

    public void print(HttpServletResponse response, Object message) {
        try {
            response.setStatus(HttpStatus.OK.value());
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.setHeader("Cache-Control", "no-cache, must-revalidate");
            PrintWriter writer = response.getWriter();
            writer.write(message.toString());
            writer.flush();
            writer.close();
        } catch (IOException e) {
            logger.error("error occurred when printing", e);
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex)
            throws Exception {
    }
}  